using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace demo
{
    /// <summary>
    /// 现代浏览器启动器，优先使用Chrome/Edge等现代浏览器，兼容Windows7、Windows10等操作系统 xp放弃
    /// </summary>
    public partial class InternalBrowserForm : Form
    {
        private WebBrowser webBrowser;
        private ToolStrip toolStrip;
        private ToolStripTextBox addressTextBox;
        private ToolStripButton goButton;
        private ToolStripButton backButton;
        private ToolStripButton forwardButton;
        private ToolStripButton refreshButton;
        private ToolStripButton homeButton;
        private StatusStrip statusStrip;
        private ToolStripStatusLabel statusLabel;
        private string initialUrl;

        public InternalBrowserForm(string url)
        {
            initialUrl = url;
            InitializeComponent();
            
            // 尝试使用现代浏览器打开URL
            if (TryOpenWithModernBrowser(url))
            {
                // 如果成功启动现代浏览器，关闭当前窗体
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                this.Load += (s, e) => this.Close();
            }
            else
            {
                // 如果无法启动现代浏览器，使用内置WebBrowser作为备选
                LoadUrl(url);
            }
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // 设置窗体属性
            this.Text = "检查检验互认结果查看器";
            this.Size = new Size(1280, 720);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.MinimumSize = new Size(800, 600);
            this.Icon = SystemIcons.Application;

            // 创建工具栏
            toolStrip = new ToolStrip();
            toolStrip.Dock = DockStyle.Top;

            // 后退按钮
            backButton = new ToolStripButton("后退");
            backButton.Click += BackButton_Click;
            backButton.Enabled = false;
            toolStrip.Items.Add(backButton);

            // 前进按钮
            forwardButton = new ToolStripButton("前进");
            forwardButton.Click += ForwardButton_Click;
            forwardButton.Enabled = false;
            toolStrip.Items.Add(forwardButton);

            // 刷新按钮
            refreshButton = new ToolStripButton("刷新");
            refreshButton.Click += RefreshButton_Click;
            toolStrip.Items.Add(refreshButton);

            // 主页按钮
            homeButton = new ToolStripButton("主页");
            homeButton.Click += HomeButton_Click;
            toolStrip.Items.Add(homeButton);

            // 分隔符
            toolStrip.Items.Add(new ToolStripSeparator());

            // 地址栏
            ToolStripLabel addressLabel = new ToolStripLabel("地址:");
            toolStrip.Items.Add(addressLabel);

            addressTextBox = new ToolStripTextBox();
            addressTextBox.Size = new Size(400, 25);
            addressTextBox.KeyDown += AddressTextBox_KeyDown;
            toolStrip.Items.Add(addressTextBox);

            // 转到按钮
            goButton = new ToolStripButton("转到");
            goButton.Click += GoButton_Click;
            toolStrip.Items.Add(goButton);

            this.Controls.Add(toolStrip);

            // 创建WebBrowser控件作为备选方案
            webBrowser = new WebBrowser();
            webBrowser.Dock = DockStyle.Fill;
            webBrowser.ScriptErrorsSuppressed = true;
            webBrowser.DocumentCompleted += WebBrowser_DocumentCompleted;
            webBrowser.Navigating += WebBrowser_Navigating;
            webBrowser.CanGoBackChanged += WebBrowser_CanGoBackChanged;
            webBrowser.CanGoForwardChanged += WebBrowser_CanGoForwardChanged;
            this.Controls.Add(webBrowser);

            // 创建状态栏
            statusStrip = new StatusStrip();
            statusStrip.Dock = DockStyle.Bottom;
            statusLabel = new ToolStripStatusLabel("就绪");
            statusStrip.Items.Add(statusLabel);
            this.Controls.Add(statusStrip);

            this.ResumeLayout(false);
            this.PerformLayout();
        }

        private bool TryOpenWithModernBrowser(string url)
        {
            if (string.IsNullOrEmpty(url))
                return false;

            // 确保URL格式正确
            if (!url.StartsWith("http://") && !url.StartsWith("https://"))
            {
                url = "http://" + url;
            }

            // 获取所有可用的浏览器并按版本排序
            var availableBrowsers = GetAvailableBrowsersWithVersions();
            
            // 按优先级和版本排序后尝试启动
            foreach (var browser in availableBrowsers.OrderBy(b => b.Priority).ThenByDescending(b => b.Version))
            {
                try
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = browser.Path,
                        Arguments = url,
                        UseShellExecute = true
                    };
                    Process.Start(startInfo);
                    return true;
                }
                catch (Exception)
                {
                    // 继续尝试下一个浏览器
                    continue;
                }
            }

            // 如果没有找到现代浏览器，尝试使用系统默认浏览器
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = url,
                    UseShellExecute = true
                };
                Process.Start(startInfo);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private List<BrowserInfo> GetAvailableBrowsersWithVersions()
        {
            var browsers = new List<BrowserInfo>();

            // 定义浏览器搜索路径和优先级
            var browserConfigs = new[]
            {
                new { Name = "Edge", Priority = 1, Paths = new[] {
                    @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
                    @"C:\Program Files\Microsoft\Edge\Application\msedge.exe"
                }},
                new { Name = "Chrome", Priority = 2, Paths = new[] {
                    @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
                    @"C:\Program Files\Google\Chrome\Application\chrome.exe",
                    @"C:\Users\" + Environment.UserName + @"\AppData\Local\Google\Chrome\Application\chrome.exe",
                    @"D:\Chrome109.0.5414.120_32\App\Chrome-bin\109.0.5414.120\chrome.exe"
                }},
                new { Name = "Firefox", Priority = 3, Paths = new[] {
                    @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe",
                    @"C:\Program Files\Mozilla Firefox\firefox.exe"
                }},
                new { Name = "Opera", Priority = 4, Paths = new[] {
                    @"C:\Program Files (x86)\Opera\launcher.exe",
                    @"C:\Program Files\Opera\launcher.exe",
                    @"C:\Users\" + Environment.UserName + @"\AppData\Local\Programs\Opera\launcher.exe"
                }},
                new { Name = "360SE", Priority = 5, Paths = new[] {
                    @"C:\Documents and Settings\Administrator\Application Data\360se6\Application\360se.exe",
                    @"C:\Users\Administrator\AppData\Roaming\360se6\Application\360se.exe",
                    @"C:\Users\" + Environment.UserName + @"\AppData\Roaming\360se6\Application\360se.exe"
                }}
        };

            foreach (var config in browserConfigs)
            {
                foreach (var path in config.Paths)
                {
                    if (File.Exists(path))
                    {
                        try
                        {
                            var versionInfo = FileVersionInfo.GetVersionInfo(path);
                            var version = new Version(versionInfo.FileMajorPart, versionInfo.FileMinorPart, versionInfo.FileBuildPart, versionInfo.FilePrivatePart);
                            
                            browsers.Add(new BrowserInfo
                            {
                                Name = config.Name,
                                Path = path,
                                Version = version,
                                Priority = config.Priority
                            });
                        }
                        catch (Exception)
                        {
                            // 如果无法获取版本信息，使用默认版本
                            browsers.Add(new BrowserInfo
                            {
                                Name = config.Name,
                                Path = path,
                                Version = new Version(0, 0, 0, 0),
                                Priority = config.Priority
                            });
                        }
                    }
                }
            }

            return browsers;
        }

        private class BrowserInfo
        {
            public string Name { get; set; }
            public string Path { get; set; }
            public Version Version { get; set; }
            public int Priority { get; set; }
            
        }

        private void LoadUrl(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                try
                {
                    // 确保URL格式正确
                    if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                    {
                        url = "http://" + url;
                    }
                    addressTextBox.Text = url;
                    webBrowser.Navigate(url);
                    statusLabel.Text = "正在加载: " + url;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("加载网页时出现错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void BackButton_Click(object sender, EventArgs e)
        {
            if (webBrowser.CanGoBack)
            {
                webBrowser.GoBack();
            }
        }

        private void ForwardButton_Click(object sender, EventArgs e)
        {
            if (webBrowser.CanGoForward)
            {
                webBrowser.GoForward();
            }
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            webBrowser.Refresh();
        }

        private void HomeButton_Click(object sender, EventArgs e)
        {
            LoadUrl(initialUrl);
        }

        private void GoButton_Click(object sender, EventArgs e)
        {
            LoadUrl(addressTextBox.Text);
        }

        private void AddressTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoadUrl(addressTextBox.Text);
                e.Handled = true;
            }
        }

        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            statusLabel.Text = "完成";
            addressTextBox.Text = webBrowser.Url?.ToString() ?? "";
        }

        private void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            statusLabel.Text = "正在导航到: " + e.Url.ToString();
        }

        private void WebBrowser_CanGoBackChanged(object sender, EventArgs e)
        {
            backButton.Enabled = webBrowser.CanGoBack;
        }

        private void WebBrowser_CanGoForwardChanged(object sender, EventArgs e)
        {
            forwardButton.Enabled = webBrowser.CanGoForward;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                webBrowser?.Dispose();
                toolStrip?.Dispose();
                statusStrip?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}